import Base64 from './base64';

export default {

    //convert string to base64   param string  return base64Str
    encode: function (str){
        let bytes = [];
        let len = str.length;
        let c,base64Str;
        for(let i=0;i<len;i++){
            c = str.charCodeAt(i);
            if(c >= 0x010000 && c <= 0x10FFFF){
                bytes.push(((c >> 18) & 0x07) | 0xF0) ;
                bytes.push(((c >> 12) & 0x3F) | 0x80) ;
                bytes.push(((c >> 6) & 0x3F) | 0x80) ;
                bytes.push((c & 0x3F) | 0x80) ;
            }else if(c >= 0x000800 && c <= 0x00FFFF){
                bytes.push(((c >> 12) & 0x0F) | 0xE0) ;
                bytes.push(((c >> 6) & 0x3F) | 0x80) ;
                bytes.push((c & 0x3F) | 0x80) ;
            }else if(c >= 0x000080 && c <= 0x0007FF){
                bytes.push(((c >> 6) & 0x1F) | 0xC0) ;
                bytes.push((c & 0x3F) | 0x80) ;
            }else{
                bytes.push(c & 0xFF)
            }
        }
        //console.log(bytes);
        base64Str = Base64.fromByteArray(bytes);
        return base64Str;
    },
    //convert baser64 to string  param base64Str return string
    incode:function (base64Str) {
        let bytes = Base64.toByteArray(base64Str);
        let str = '';
        for(let i=0; i<bytes.length; i++){
            let one = bytes[i].toString(2);
            let v = one.match(/^1+?(?=0)/);
            if(v && one.length == 8){
                let bytesLength = v[0].length;
                let store = bytes[i].toString(2).slice(7-bytesLength);
                for(let m=0; m < bytesLength; m++){
                    store += bytes[m+i].toString(2).slice(2); 
                }
                str += String.fromCharCode(parseInt(store,2));
                i += bytesLength -1;
            }else{
                str += String.fromCharCode(bytes[i]);
            }
        }
        return str;
    }
 }